package miniox

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/zeromicro/go-zero/core/logx"
)

// InitMinio minio初始化
func InitMinio(Endpoint, AccessKey, SecretKey, bucket string) *minio.Client {
	// 连接到 MinIO 集群
	endpoint := Endpoint
	accessKey := AccessKey
	secretKey := SecretKey
	useSSL := false

	// 创建一个MinIO客户端对象
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKey, secretKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		logx.Error("连接minio失败, error=", err)
		panic("连接minio失败, error=" + err.Error())
	}
	status, err := minioClient.BucketExists(context.TODO(), bucket)
	if err != nil {
		logx.Error("查询桶是否存在失败, error=", err)
		panic("查询桶是否存在失败, error=" + err.Error())
	}
	if !status {
		err := minioClient.MakeBucket(context.TODO(), bucket, minio.MakeBucketOptions{})
		if err != nil {
			logx.Error("创建桶失败, error=", err)
			panic("创建桶失败, error=" + err.Error())
		}
	}

	fmt.Println("连接minio成功")
	return minioClient
}
